// pages/addressEdit/addressEdit.js
let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    editAddress: false,
    page_title: '请输入您的居住地址',
    submitBtn: '验证并提交',
    region: ['广东省', '广州市', '天河区'],
    customItem: ''
  },

  bindResetAddress: function(e) {
    this.setData({
      editAddress: true
    });
  },

  bindRegionChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region: e.detail.value
    })
  },

  formSubmit: function(e) {
    console.log(e.detail.value);

    if (this.data.editAddress) {
      if (e.detail.value.address1 == '' || e.detail.value.address2 == '') {
        wx.showToast({
          title: '地址不能为空',
          icon: 'none',
          image: '../images/fail.png',
          duration: 2000
        });
        return false;
      }

      var reg = new RegExp("^([\\u4E00-\\u9FA5A-Za-z0-9_]+(道|路|街|号|村)){2,}");
      if (!reg.test(e.detail.value.address2)) {
        wx.showToast({
          title: '详细地址需要精确到街道、路、门牌号',
          icon: 'none',
          duration: 2000
        });
        return false;
      }
    }

    try {
      var currentUser = wx.getStorageSync('callUser')
      if (currentUser) {
        // Do something with return value
        let params = {
          phoneNum: parseInt(currentUser.phoneNum),
          userid: (new Date()).getTime()
        };

        wx.setStorage({
          key: 'userid',
          data: params.userid,
        });
        // 发送当前接听的用户给后台，返回该用户的相关语音链接
        const url_callUser = app.globalData.baseUrl + '/chat';

        if (this.data.editAddress) {
          params.address = e.detail.value.address1 + e.detail.value.address2;
          wx.showLoading({
            title: '验证中，请等待',
          });

          wx.request({
            url: 'https://api.map.baidu.com/geocoder/v2/?address=' + params.address + '&output=json&ak=RNjDarowOS0rarZMjb4GXBsFlyde0VGQ',
            dataType: 'json',
            success: function(res) {
              console.log(res.data);
              if (res.data.result.level == '区县' || res.data.result.level == 'UNKNOWN') {
                wx.hideLoading();
                wx.showToast({
                  title: '详细地址不正确，请重新输入',
                  icon: 'none',
                  duration: 2000
                });
                return false;
              }

              // 地址验证正确后，调取后台保存
              wx.request({
                url: url_callUser,
                data: params,
                header: {
                  'content-type': 'application/x-www-form-urlencoded'
                },
                method: 'POST',
                success: function (res) {

                  if (res.data.status == 'Running') {
                    wx.setStorage({
                      key: 'curUserAudio',
                      data: res.data,
                    });
                    wx.redirectTo({
                      url: '/pages/calling/calling',
                    })
                  }
                },
                fail: function (error) {
                  console.log('calling send msg', error.errMsg);
                },
                complete: function () {
                  wx.hideLoading();
                }
              })
            },
            fail: function() {

            },
            complete: function() {

            }
          })
          return false;

        }

        // 未修改的地址的调用后台
        wx.showLoading({
          title: '呼叫中，请等待',
        });

        wx.request({
          url: url_callUser,
          data: params,
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          method: 'POST',
          success: function(res) {

            if (res.data.status == 'Running') {
              wx.setStorage({
                key: 'curUserAudio',
                data: res.data,
              });
              wx.redirectTo({
                url: '/pages/calling/calling',
              })
            }
          },
          fail: function(error) {
            console.log('calling send msg', error.errMsg);
          },
          complete: function() {
            wx.hideLoading();
          }
        })

      }
    } catch (e) {
      // Do something when catch error
    }

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      editAddress: false
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  }
})